package ee.tlnk.service;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
 * The Class OrderServlet.
 */
public class OrderServlet extends HttpServlet {
    
    /** The Constant serialVersionUID. */
	private static final long serialVersionUID = 41292763306995785L;
    
    /** The Constant url. */
    private static final String url = "http://localhost:8080/fixation/rest/order/";


	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	public void doPost( HttpServletRequest request,
                      HttpServletResponse response)

            throws ServletException, IOException {
		
		RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/views/order.jsp");
		String action = request.getParameter("action");

		if ("addorder".equals(action))
		{
			String managerId = (String) request.getParameter("manager");
			String roomId = (String) request.getParameter("room");
			String dayRequest = (String) request.getParameter("date");
			String timeStart = (String) request.getParameter("start");
			String timeEnd = (String) request.getParameter("end");

		String xml  = "<order><room>"
				+roomId+"</room><manager>"
				+managerId+"</manager><date>"
				+dayRequest+"</date><start>"
				+timeStart+"</start><end>"
				+timeEnd+"</end></order>";
		HttpClient client = new HttpClient();
		client.getHttpConnectionManager().getParams()
				.setConnectionTimeout(5000);
		PostMethod method = new PostMethod(url + "postxml/");
		method.setRequestEntity(new StringRequestEntity(xml, MediaType.APPLICATION_XML , "UTF-8"));
		int retc = client.executeMethod(method);
		String responseBody = method.getResponseBodyAsString();
		if (!"".equals(responseBody)) {
			request.setAttribute("response", "Success");
		} else
		{
			request.setAttribute("response", "Unsuccess");
			response.setStatus(retc);
		}
		}
	}
}